package com.squareup.picasso;

import android.net.NetworkInfo;

import com.squareup.picasso.Picasso.LoadedFrom;

import java.io.IOException;
import java.io.InputStream;

final class NetworkRequestHandler extends RequestHandler {
    static final int RETRY_COUNT = 2;

    class ContentLengthException extends IOException {
        public ContentLengthException(String arg1) {
            super(arg1);
        }
    }

    private final Stats stats;

    public NetworkRequestHandler(Stats stats) {
        this.stats = stats;
    }

    final int getRetryCount() {
        return RETRY_COUNT;
    }

    final boolean shouldRetry(NetworkInfo networkInfo) {
        return networkInfo == null || networkInfo.isConnected();
    }

    public final boolean canHandleRequest(Request result) {
        String scheme = result.uri.getScheme();
        return "http".equals(scheme) || "https".equals(scheme);
    }

    public final Result load(Request request) throws IOException {
        Downloader.Response response = Downloader.load(request.uri, request.networkPolicy);
        LoadedFrom loadedFrom = LoadedFrom.NETWORK;
        InputStream inputStream = response.stream;
        if (inputStream == null) {
            return null;
        } else {
            if (loadedFrom == LoadedFrom.DISK && response.length == 0L) {
                Utils.closeQuietly(inputStream);
                throw new ContentLengthException("Received response with 0 content-length header.");
            }
            if (loadedFrom == LoadedFrom.NETWORK && response.length > 0L) {
                this.stats.handler.sendMessage(this.stats.handler.obtainMessage(4, Long.valueOf(response.length)));
            }
            return new Result(inputStream, loadedFrom);
        }
    }
    final boolean supportsReplay() {
        return true;
    }
}

